package com.yunyun400.vosk.service;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yunyun400.vosk.entity.ReminderRecord;
import com.yunyun400.vosk.service.EmailNotificationService;

/**
 * 提醒服务
 * 负责管理检测到关键词的录音文件提醒
 */
@Service
public class ReminderService {
    
    private static final Logger logger = LoggerFactory.getLogger(ReminderService.class);
    
    // 模拟存储提醒记录的列表（实际项目中应该使用数据库）
    private List<ReminderRecord> reminderRecords = new ArrayList<>();
    
    @Autowired
    private RecordingService recordingService;
    
    @Autowired
    private EmailNotificationService emailNotificationService;
    
    /**
     * 执行录音检查并创建提醒
     * @param batchId 关联的外呼批次ID
     * @return 处理过的录音文件路径列表
     */
    public List<String> checkRecordingsAndCreateReminders(String batchId) {
        logger.info("开始检查录音文件并创建提醒，批次ID: {}", batchId);
        
        // 记录所有处理过的文件路径
        List<String> processedFiles = new ArrayList<>();
        
        // 处理所有录音文件
        List<String> filesWithKeyword = recordingService.processAllRecordings();
        processedFiles.addAll(filesWithKeyword);
        
        // 为每个包含关键词的文件创建提醒记录
        int createdCount = 0;
        
        ReminderRecord recordAll = new ReminderRecord();
        recordAll.setRecordingFileName("菲律宾电话记录");
        recordAll.setBatchId(batchId);
        List<String> recordFiles = new ArrayList<String>();
        for (String filePath : filesWithKeyword) {
            try {
            	Path path = Paths.get(filePath);
                // 获取文件名（包含扩展名）
                String fileName = path.getFileName().toString(); // 注意需要转为字符串
                
                recordFiles.add(fileName.split("_")[0].replace("88889", "").substring(0,3));

                ReminderRecord record = new ReminderRecord(filePath);
                record.setId(UUID.randomUUID().toString());
                record.setBatchId(batchId);
                
                // 添加到提醒记录列表
                reminderRecords.add(record);
                createdCount++;
                
                logger.info("已创建提醒记录: {}", record);
            } catch (Exception e) {
                logger.error("为文件 {} 创建提醒记录时发生错误", filePath, e);
            }
        }
        
    	recordAll.setRecords(recordFiles);
        
     // 发送邮件通知
        boolean notificationSent = emailNotificationService.sendReminderEmail(recordAll);
        if (notificationSent) {
            logger.info("已成功发送邮件提醒，提醒ID: {}", recordAll.getId());
        } else {
            logger.warn("邮件提醒发送失败，提醒ID: {}", recordAll.getId());
        }
        
        
        
        logger.info("录音检查完成，共创建 {} 个提醒记录", createdCount);
        return new ArrayList<>(filesWithKeyword);
    }
    
    /**
     * 获取所有提醒记录
     */
    public List<ReminderRecord> getAllReminders() {
        return new ArrayList<>(reminderRecords);
    }
    
    /**
     * 获取未处理的提醒记录
     */
    public List<ReminderRecord> getUnprocessedReminders() {
        List<ReminderRecord> unprocessed = new ArrayList<>();
        for (ReminderRecord record : reminderRecords) {
            if (!record.isProcessed()) {
                unprocessed.add(record);
            }
        }
        return unprocessed;
    }
    
    /**
     * 标记提醒记录为已处理
     */
    public boolean markAsProcessed(String reminderId) {
        for (ReminderRecord record : reminderRecords) {
            if (record.getId().equals(reminderId)) {
                record.setProcessed(true);
                logger.info("已将提醒记录 {} 标记为已处理", reminderId);
                return true;
            }
        }
        logger.warn("未找到ID为 {} 的提醒记录", reminderId);
        return false;
    }
    
    /**
     * 根据批次ID获取提醒记录
     */
    public List<ReminderRecord> getRemindersByBatchId(String batchId) {
        List<ReminderRecord> batchReminders = new ArrayList<>();
        for (ReminderRecord record : reminderRecords) {
            if (batchId != null && batchId.equals(record.getBatchId())) {
                batchReminders.add(record);
            }
        }
        return batchReminders;
    }
}